package com.fullhome8.cn.wanghongweb.redis;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;

/**
 * 操作Redis的类
 */
@Slf4j
@Component
public class RedisUtil {

	 @Value("${application.redis.host}")
    private String host;

    @Value("${application.redis.port}")
    private Integer port;

    @Value("${application.redis.maxInst}")
    private Integer maxInst;

    @Value("${application.redis.coreInst}")
    private Integer maxIdle;

    @Value("${application.redis.maxWait}")
    private Integer maxWait;

    @Value("${application.redis.establishConnTimeout}")
    private Integer establishConnTimeout;

    @Value("${application.redis.password}")
    private String password;
    
    private JedisPool jedisPool;

    private RedisUtil() {

    }

    @PostConstruct
    private void init() {
        JedisPoolConfig conf = new JedisPoolConfig();
        conf.setMaxTotal(maxInst);
        conf.setMaxIdle(maxIdle);
        conf.setMaxWaitMillis(maxWait);
        conf.setTestOnBorrow(true);
        try {
            if (jedisPool == null || (jedisPool != null && jedisPool.isClosed())) {
                if (StringUtils.isNotEmpty(password)) {
                    jedisPool = new JedisPool(conf, host, port,establishConnTimeout,password);
                } else {
                    jedisPool = new JedisPool(conf, host, port,establishConnTimeout);
                }
            }
        } catch (Exception e) {
            log.error("can not create JedisPool.", e);
        }
    }

    /**
     * 获取Jedis连接
     * 
     * @return
     */
    public Jedis getConnection() {
        Jedis jedis = null;
        if (jedisPool != null && !jedisPool.isClosed()) {
            try {
                jedis = jedisPool.getResource();
            } catch (Exception e) {
                close(jedis);
                log.error("can not get jedis from JedisPool.", e);
            }
        } else {
            log.error("JedisPool is closed!");
            throw new RuntimeException("JedisPool is closed!");
        }
        return jedis;
    }

    /**
     * 关闭Jedis连接
     * 
     * @param jedis
     */
    public void close(Jedis jedis) {
        if (jedis != null) {
            try {
                jedis.close();
            } catch (Exception e) {
                log.error("can not return jedis to JedisPool.", e);
            }
        }
    }

}
